/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pin.db.dbcp;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

/**
 *
 * @author didyhu
 */
public class Dbcp {

    private static DataSource ds = null;

    public static DataSource createDataSource(String propertiesFilename) throws SQLException {
        try {
            String loaderPath = Dbcp.class.getClassLoader().getResource(".").toString();
            System.out.println(loaderPath);
            InputStream is = Dbcp.class.getClassLoader().getResourceAsStream("META-INF/" + propertiesFilename);
            Properties p = new Properties();
            try {
                p.load(is);
            } catch (IOException ex) {
                throw new SQLException(ex);
            } catch (NullPointerException ex) {
                throw new SQLException("properties file NOT found");
            }
            return BasicDataSourceFactory.createDataSource(p);
        } catch (Exception ex) {
            Logger.getLogger(Dbcp.class.getName()).log(Level.SEVERE, null, ex);
            throw new SQLException(ex);
        }
    }

    public static Connection getConnection() throws SQLException {
        if (ds == null) {
            ds = createDataSource("dbcp.properties");
        }

        return ds.getConnection();
    }
}
